<template>
<LayoutView :select-index="100">
  <div class="article" style="background-color: #FAF9DE;padding: 15px;width: 960px;margin: 10px auto">
    <h3 style="text-align: center">{{catalog.catalog.catalogName}}</h3>
    <div class="ql-editor" v-html="catalog.catalog.content"></div>
    <div class="opt" style="text-align: center">
      <el-button type="text" :disabled="catalog.prevId === undefined" @click="change(catalog.prevId)">上一章</el-button>
      <el-button type="text" @click="showMenu = !showMenu">目录</el-button>
      <el-button type="text" :disabled="catalog.nextId === undefined" @click="change(catalog.nextId)">下一章</el-button>
    </div>
  </div>
  <div v-if="showMenu" style="width: 170px;position: fixed;left: 5px;top:80px;border: 1px solid #e6e6e6">
    <el-menu :collapse-transition="false" :default-active="catalog.catalog.id">
      <el-menu-item v-for="item in catalogList" :key="item.id" :index="item.id" @click="change(item.id)">
        <span :title="item.catalogName" style="display: inline-block;width: 170px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">{{item.catalogName}}</span>
      </el-menu-item>
    </el-menu>
  </div>
</LayoutView>
</template>

<script>
import LayoutView from '@/views/front/components/LayoutView.vue'
export default {
  name: 'ReadView',
  components: { LayoutView },
  data () {
    return {
      bookId: '',
      catalogId: '',
      loginId: '',
      catalog: {},
      catalogList: [],
      showMenu: false,
      inter: ''
    }
  },
  methods: {
    getCatalog () {
      this.setScroll()
      this.$http.post('api/book/read', { userId: this.loginId, bookId: this.bookId, catalogId: this.catalogId }).then(({ data }) => {
        this.catalog = { ...data }
      }).catch(() => {
        this.$router.back()
      })
    },
    getCatalogList () {
      this.$http.get(`api/book/${this.bookId}/catalog`).then(({ data }) => {
        this.catalogList = [...data]
      })
    },
    change (catalogId) {
      this.catalogId = catalogId
      this.getCatalog()
    },
    setScroll () {
      /* 获取滚动条高度 */
      let scrollTop = document.documentElement.scrollTop
      /* 设置间距 */
      let steep = scrollTop / 2000
      this.inter = setInterval(() => {
        /* 滚动的速度逐渐变快，第一次走2000/1，然后减去已走的距离，下一次用剩下的距离再减去步进值，步进值也是不断变化，这样速度会越来越快 */
        scrollTop -= steep
        /* 步进值不改变的话会匀速缓慢上滑，不断增加步进值上滑的距离增加，视觉效果速度变快 */
        steep += 20
        if (scrollTop <= 0) {
          clearInterval(this.inter)
        }
        document.documentElement.scrollTop = scrollTop
      }, 30)
    }
  },
  created () {
    this.bookId = this.$route.query.bookId
    this.catalogId = this.$route.query.catalogId
    this.loginId = JSON.parse(sessionStorage.getItem('vipInfo'))?.loginInfo?.userId
    if (this.loginId) {
      this.getCatalog()
      this.getCatalogList()
    } else {
      this.$message.error('请先登录！')
      this.$router.replace('/')
    }
  }
}
</script>

<style scoped>

</style>
